const express = require('express')
const { queryDBPromise } = require('../db/db')
const cartRouter = express.Router()

/**
 * 加入购物车
 */
cartRouter.post('/cart', (req, res) => {
	//接收参数
	const name = req.body.name // 商品名称
	const url = req.body.url // 商品图片
	const price = req.body.price //商品价格
	const num = req.body.num //商品数量
	const description = req.body.description // 商品描述
	const state = req.body.state // 是否选中

	// 保存数据
	const sql = `INSERT INTO cart (name,url,price,num,description,state)VALUES('${name}','${url}',${price},${num},'${description}',${state})`
	queryDBPromise(sql).then(data => {
		res.send({
			code: 1,
			message: '添加购物车成功!',
		})
	})
})

/**
 * 购物车列表
 */
cartRouter.get('/carts', (req, res) => {
	const sql = 'SELECT id, name,url,price,num,description,state FROM cart'
	queryDBPromise(sql).then(data => {
		res.send({
			code: 1,
			list: data,
		})
	})
})

/**
 * 数量操作
 *   method: put
 *   url: /cart/1
 *   参数：type:add
 */
cartRouter.put('/cart/:id', (req, res) => {
	const id = req.params.id // 购物项ID
	const type = req.body.type // 加减操作

	const sql = `SELECT num  FROM cart WHERE id = ${id}`
	queryDBPromise(sql).then(data => {
		const num = data[0].num
		const sql = `UPDATE cart SET num = ${type == 'add' ? num + 1 : num - 1} WHERE id = ${id}`
		queryDBPromise(sql).then(data => {
			res.send({
				code: 1,
				message: '数量修改成功!',
			})
		})
	})
})


/**
 * 单选
 */
cartRouter.put('/cart/state/:id',(req,res)=>{
    const id = req.params.id // 购物车项ID
    const sql = `SELECT state FROM cart WHERE id = ${id}`
    queryDBPromise(sql).then(data=>{
        const state = data[0].state
        const sql = `UPDATE cart SET state = ${state==0?1:0} WHERE id=${id}`
        queryDBPromise(sql).then(data=>{
            res.send({
                code:1,
                message:'选中成功'
            })
        })

    })
})

/**
 * 全选
 */
cartRouter.put('/cart/check/state',(req,res)=>{
    const checkState = req.body.checkstate // 全选状态 0,未全选，1，全选
    const sql = `UPDATE cart SET state = ${checkState}`
    queryDBPromise(sql).then(data=>{
        res.send({
            code:1,
            message:'设置成功!'
        })
    })
})


/**
 * 判断商品是否已经存在购物车中
 */
cartRouter.get('/cart/ischeck',(req,res)=>{
	const name = req.query.name //商品名称

	const sql = `SELECT id FROM cart WHERE name = '${name}'`
	queryDBPromise(sql).then(data=>{
		console.log('data[0] ',data[0]);
		
		if(data[0]?.id > 0){
			res.send({
				code:-1,
				message:'商品已经存在!',
				id: data[0].id
			})

		}else{
			res.send({
				code:1,
				message:'商品不存在!'
			})
		}
    })
})

/**
 * 计算总价
 */
cartRouter.post('/cart/totalprice',(req,res)=>{
	const sql = 'SELECT  sum(cart.price*cart.num) AS total FROM cart WHERE state = 1'
	queryDBPromise(sql).then(data=>{
		
		const total = data[0].total
        res.send({
            code:1,
            total:total
        })
    })
})

module.exports = {cartRouter}